package taskTracker.ui.lite;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import taskTracker.Project;
import taskTracker.Task;
import taskTracker.util.Helper;


/**
 * A form used to add/edit tasks;
 * @author aseldawy
 *
 */
public class TaskForm extends Form {

	/**Command for accepting changes when creating an existing project*/
	public final Command cmdCreate = new Command("Ok", Command.OK, 1);
	
	/**Command for accepting changes when updating an existing project*/
	public final Command cmdUpdate = new Command("Ok", Command.OK, 1);
	public final Command cmdCancel = new Command("Cancel", Command.CANCEL, 1);
	private final TextField txtName = new TextField("Name", "", 64, TextField.ANY);
	private final TextField txtNotes = new TextField("Notes", "", 64, TextField.ANY);
	private final TextField txtDueTo = new TextField("DueTo", "", 64, TextField.ANY);
	/**Checkbox for whether this is trackable or not*/
	private final ChoiceGroup chkTrackable = new ChoiceGroup("", ChoiceGroup.MULTIPLE, new String[] {"Trackable"}, null);
	/**Text area that holds tags*/
	private final TextField txtTags = new TextField("Tags", "", 64, TextField.ANY);
	/**The task currently being edited/created */
	private Task task;
	/**
	 * The project that this task belongs to.
	 * Used when creating a new task to add it to the correct project
	 */
	private final Project project;
	
	public TaskForm(Project project, Task task) {
		super("");
		super.append(txtName);
		super.append(txtNotes);
		super.append(txtDueTo);
		super.append(chkTrackable);
		super.append(txtTags);

		super.addCommand(task == null ? cmdCreate : cmdUpdate);
		super.addCommand(cmdCancel);
		this.project = project;
		this.setTask(task);
	}

	private void setTask(Task task) {
		if (task == null) {
			super.setTitle("New Task");
			txtName.setString("");
			txtNotes.setString("");
			txtTags.setString("");
			txtDueTo.setString(Helper.dateToString(System.currentTimeMillis()));
			chkTrackable.setSelectedIndex(0, false);
		} else {
			super.setTitle(task.getName());
			txtName.setString(task.getName());
			txtNotes.setString(task.getNotes());
			txtTags.setString(task.getTagsAsString());
			txtDueTo.setString(Helper.dateToString(task.getDueTo()));
			chkTrackable.setSelectedIndex(0, task.isTrackable());
		}
		this.task = task;
	}

	/**
	 * Retrieves data of task stored in this dialog
	 * @param taskList
	 * @return
	 */
	public Task getTask() {
		if (task == null) {
			task = new Task(txtName.getString(), txtNotes.getString());
		} else {
			task.setName(txtName.getString());
			task.setNotes(txtNotes.getString());
		}
		task.setDueTo(Helper.decodeDate(txtDueTo.getString()));
		task.setTrackable(chkTrackable.isSelected(0));
		task.setTags(txtTags.getString());
		return task;
	}

	public Project getProject() {
		return project;
	}
}
